#include "stdafx.h"
#include "InternetAddress.h"
#include <cstring>

namespace Core
{

	InternetAddress::InternetAddress()
	{
		Address = "";
		PortNumber = 0;
	}

	InternetAddress::InternetAddress(sockaddr_in& p_SockAddrIn)
	{
		SetSockAddrIn(p_SockAddrIn);
	}

	InternetAddress::InternetAddress(std::string p_Address, unsigned short p_PortNumber)
	{
		Address = p_Address;
		PortNumber = p_PortNumber;
	}

	void InternetAddress::SetSockAddrIn(sockaddr_in& p_SockAddrIn)
	{
		Address = inet_ntoa(p_SockAddrIn.sin_addr);
		PortNumber = ntohs(p_SockAddrIn.sin_port);
	}

	struct sockaddr_in InternetAddress::GetSockAddrIn()
	{
		struct sockaddr_in t_SockAddrIn;
		t_SockAddrIn.sin_family = AF_INET;
		t_SockAddrIn.sin_port = htons(PortNumber);
		if(Address!="")
		{
			t_SockAddrIn.sin_addr.s_addr = inet_addr(Address.c_str());
		}
		else
		{
			t_SockAddrIn.sin_addr.s_addr = INADDR_ANY;
		}
		memset(&t_SockAddrIn.sin_zero, '\0', 8);
		return t_SockAddrIn;
	}

	unsigned long InternetAddress::GetAddress()
	{
		struct sockaddr_in t_SockAddrIn = GetSockAddrIn();
#ifdef WIN32
		return t_SockAddrIn.sin_addr.S_un.S_addr;
#else
		return t_SockAddrIn.sin_addr.s_addr;
#endif
	}

	void InternetAddress::SetAddress(unsigned long p_Address)
	{
		struct sockaddr_in t_SockAddrIn;
#ifdef WIN32
		t_SockAddrIn.sin_addr.S_un.S_addr = p_Address;
#else
		t_SockAddrIn.sin_addr.s_addr = p_Address;
#endif
		Address = inet_ntoa(t_SockAddrIn.sin_addr);
	}
}
